package com.training.java.redbox.domain;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

@Repository
public class OrdersDAOJDBCImpl implements OrdersDAO {

	@Autowired
	private JdbcTemplate jdbcTemplate;
	
	@Override
	public List<Orders> getAllOrders() throws DAOException {
		
		return jdbcTemplate.query("select * from Orders", new OrdersRowMapper());
	}

	@Override
	public void createOrders(Orders orders) throws DAOException {
		
		jdbcTemplate.update("insert into orders values(order_id_seq.nextval,?,?,?,?)", orders.getOrderNumber(),
				orders.getCustomer_id(),orders.getMovie_id(),orders.getStatus());
	}

	@Override
	public Orders getOrdersById(long id) throws DAOException {
		
		try{
		return jdbcTemplate.queryForObject("select * from order where orderId = ?", new OrdersRowMapper(), id);
		}catch(EmptyResultDataAccessException erdae){
			return null;
		}
	}

	
	@Override
	public void delete(long id) throws DAOException {
		
		jdbcTemplate.update("delete from orders where id = ?", id);
		
	}
	
	
	@Override
	public long createOrderNumber() throws DAOException {
		
		return jdbcTemplate.queryForLong("select order_num_seq.nextval from dual");
		
	}
	

	private static final class OrdersRowMapper implements RowMapper<Orders>{

		@Override
		public Orders mapRow(ResultSet rs, int rowNum) throws SQLException {
			
			long orderNumber = rs.getLong("orderNumber");
			long orderId = rs.getLong("orderId");
			long customer_id = rs.getLong("customer_id");
			long movie_id = rs.getLong("movie_id");
			String status = rs.getString("status");

			Orders orders = new Orders(orderNumber, orderId, customer_id, movie_id,
					status);
			
			return orders;
		}
		
	}


}
